package com.qf.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.commons.JwtUtil;
import com.qf.entity.R;
import com.qf.entity.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2020-09-25 10:35:07
 */
@RestController
@RequestMapping("/user")
public class UserController  {
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public R<Boolean> register(User user){
        boolean flag = true;
        try {
            flag = userService.save(user);
        } catch (Exception e) {
            return new R<Boolean>().setCode(R.Code.ERROR).setMsg("用户名已存在！").setData(flag);
        }

        return new R<Boolean>().setData(flag);
    }


    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public R<String> login(String username, String password, String devid){
        //用户信息
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username).eq("password", password));

        if (user != null) {
            //登录成功
            System.out.println("登录成功！");

            //通过jwt生成用户令牌
            String token = JwtUtil.createToken(user, devid);
            return new R<String>().setData(token);
        }

        //登录失败
        return new R<String>().setCode(R.Code.ERROR).setMsg("账号或者密码错误!");
    }
}